package com.chenzouquan.util.verify;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JsonSyntaxValidator  {
    public static boolean validateJsonSyntax(String jsonFilePath) {
        try {
            // 预处理
            String content = new String(Files.readAllBytes(Paths.get(jsonFilePath)));
            content = content.replace("\"[","\"").replace("]\"","\"");
            // 将修改后的JSON字符串写回文件
            Files.write(Paths.get(jsonFilePath), content.getBytes());

            // 读取JSON文件
            File jsonFile = new File(jsonFilePath);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonFile);

            // 验证JSON语法
            return true; // JSON语法正确
        } catch (JsonParseException e) {
            System.out.println("JSON语法错误：" + e.getMessage());
        } catch (IOException e) {
            System.out.println("无法读取JSON文件：" + e.getMessage());
        }
        return false;
    }

    public static void main(String[] args) {
        String jsonFilePath = "C:\\Users\\cheng\\Desktop\\test.json";
        boolean isValid = validateJsonSyntax(jsonFilePath);
        if (isValid) {
            System.out.println("JSON语法正确");
        } else {
            System.out.println("JSON语法错误或无法读取JSON文件");
        }
    }
}
